<template>
  <div class="container" ref="mainCon">
    <el-row class="searchInputWidth" style="padding-top: 24px !important">
      <el-form :inline="true" :model="filterField" ref="listForm">
        <el-col :lg="8" :xl="6">
          <el-form-item label="地区选择" class="row-padding-bottom">
            <el-cascader
              ref="areas"
              v-model="filterFieldArea"
              :options="areasOptions"
              @change="getAreaIdSearch"
              clearable
              filterable
              placeholder="请选择"
              class="proInputWidth"
              :props="{ checkStrictly: false }"
              :append-to-body="false"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :lg="8" :xl="6">
          <el-form-item label="行业选择" class="row-padding-bottom">
            <el-select
              clearable
              filterable
              placeholder="请选择"
              class="proInputWidth"
              v-model="filterField.industryId"
              :popper-append-to-body="false"
            >
              <el-option
                v-for="item in industryOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-form-item>
          <!-- <el-button
            type="primary"
            icon="icon iconfont iconchazhao1"
            @click="searchTable"
            class="commonBtn"
          /> -->
          <el-button
            type="primary"
            icon="icon iconfont iconchazhao1"
            @click="searchTable"
            class="searchBtn"
          >
            <span>搜索</span>
          </el-button>
          <!-- <el-button
            class="commonBut saveBtn funComBut"
            icon="iconfont icontianjia"
            @click="onAdd"
            v-show="isShowAdd"
          >
            <span class="opetareText">新增设置</span>
          </el-button> -->
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 列表 -->
    <div class="spacing"></div>
    <div
      ref="tableBox"
      :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
    >
      <div style="margin-bottom: 24px" v-if="isShowAdd">
        <el-button
          class="commonBut saveBtn funComBut"
          icon="iconfont icontianjia"
          @click="onAdd"
        >
          <span class="opetareText">新增设置</span>
        </el-button>
      </div>
      <el-table
        :data="tableList"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        highlight-current-row
        stripe
        v-loading="loading"
        style="border: 1px solid #dfe6ec"
        @sort-change="sortChange"
      >
        <el-table-column prop="cityName" label="市/州" />
        <el-table-column align="center" prop="countyName" label="区/县" />
        <el-table-column align="center" prop="industryName" label="行业" />
        <el-table-column
          align="center"
          prop="scale"
          label="工资专户拨付比例"
          :formatter="formatTd"
          sortable="custom"
        >
          <template slot-scope="scope">
            {{ scope.row.scale ? scope.row.scale + '%' : '--' }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="typeDesc"
          label="拨付方式"
          :formatter="formatTd"
        />
        <el-table-column align="left" label="操作" width="130px" fixed="right">
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="onUpdate(scope.$index, scope.row)"
              v-show="isShowUpdate"
              >修改</el-link
            >
            <el-link
              type="primary"
              @click="onDel(scope.row.id)"
              v-show="isShowDel"
              >删除</el-link
            >
          </template>
          <span v-show="!isShowDel && !isShowUpdate">--</span>
        </el-table-column>
        <!-- 表格数据为空时，页面显示 -->
        <div slot="empty" v-show="isEmpty">
          <emptyTable emptyText="暂无相关信息" />
        </div>
      </el-table>
      <!-- filterField为搜索条件 -->
      <Pagination
        ref="pagination"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
      />
    </div>
    <div>
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="640px"
        :modal-append-to-body="false"
        :append-to-body="true"
        @close="closeDialog('formRef')"
      >
        <el-form
          class="mrT8"
          :model="formData"
          ref="formRef"
          :rules="rules"
          label-width="150px"
        >
          <el-form-item label="区域：" prop="areaId">
            <el-cascader
              ref="areas"
              v-model="formArea"
              :options="areasOptions"
              @change="getAreaId"
              clearable
              filterable
              placeholder="请选择"
              class="dialogSingleInp"
              :props="{ checkStrictly: true }"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="行业：" prop="industryArray">
            <el-select
              clearable
              filterable
              multiple
              placeholder="请选择"
              class="dialogSingleInp"
              v-model="formData.industryArray"
            >
              <el-option
                v-for="item in industryOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="工资专户拨付比例："
            prop="scale"
            class="agreementBox"
          >
            <el-input
              v-model.trim="formData.scale"
              placeholder="请输入工资专户拨付比例"
              class="dialogSingleHalfInp"
              style="margin-right: 8px"
            ></el-input
            >%
          </el-form-item>
          <el-form-item label="拨付方式：" prop="type">
            <el-select
              clearable
              filterable
              placeholder="请选择"
              class="dialogSingleInp"
              v-model="formData.type"
            >
              <el-option
                v-for="item in bursetype"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog('formRef')" class="cancel"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="onSave"
            :loading="isSaveLoading"
            v-show="isShowSave"
            class="save"
            >保 存</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'

export default {
  name: 'allocatedSetList',

  data() {
    const validateAcquaintance = (rule, value, callback) => {
      if (value < 0 || value > 100) {
        callback(new Error('请输入1-100的数字'))
      } else {
        callback()
      }
    }
    return {
      requestUrl: 'api-acc/cs/accassconfig/expand/findbypage',
      filterField: {
        areaId: '',
        industryId: '',
      },
      tableList: [],
      loading: false,
      isEmpty: false,
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        id: '',
        areaId: '',
        industryArray: [],
        scale: '',
        type: '',
      },
      rules: {
        areaId: [{ required: true, message: '请选择区域', trigger: 'change' }],
        industryArray: [
          { required: true, message: '请选择行业', trigger: 'change' },
        ],
        scale: [
          {
            required: true,
            message: '工资专户拨付比例不能为空',
            trigger: 'blur',
          },
          {
            type: 'number',
            message: '工资专户拨付比例为数字值',
            trigger: 'blur',
            transform: (value) => Number(value),
          },
          { validator: validateAcquaintance, trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择拨付方式', trigger: 'change' },
        ],
      },
      isSaveLoading: false,
      filterFieldArea: [],
      formArea: [],
      bursetype: [],
      isShowDel: '',
      isShowUpdate: '',
      isShowAdd: '',
      isShowSave: '',
    }
  },
  computed: { ...mapState(['areasOptions', 'industryOptions']) },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, true)
    let that = this
    this.$nextTick(function () {
      let tableHeightCur = this.$refs.tableBox1.$el.clientHeight
      let tableTop = this.$refs.tableBox.getBoundingClientRect().top
      if (tableHeightCur + tableTop > window.innerHeight) {
        this.tableHeight =
          this.$refs.mainCon.getBoundingClientRect().height - 86
      } else {
        document.getElementsByClassName('tableBoxCur').length &&
          (document.getElementsByClassName('tableBoxCur')[0].style.height =
            window.innerHeight - tableTop - 28 + 'px')
      }

      window.onresize = function () {
        if (!that.$refs.tableBox1) {
          return
        }
        let tableHeightCur = that.$refs.tableBox1.$el.clientHeight
        let tableTop = that.$refs.tableBox.getBoundingClientRect().top
        if (tableHeightCur + tableTop > window.innerHeight) {
          that.tableHeight =
            that.$refs.mainCon.getBoundingClientRect().height - 86
        } else {
          document.getElementsByClassName('tableBoxCur').length &&
            (document.getElementsByClassName('tableBoxCur')[0].style.height =
              window.innerHeight - tableTop - 40 + 'px')
        }
      }
    })
  },
  deactivated() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  beforeDestroy() {
    let that = this
    window.removeEventListener('scroll', that.handleScroll, true)
  },
  created() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getIndustry({})
    this.getBursetype() //获取拨付设置
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('allocatedSet:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('allocatedSet:update') > -1
    this.isShowDel =
      this.$store.state.buttonLimitsArr.indexOf('allocatedSet:delete') > -1
    this.isShowSave =
      this.$store.state.buttonLimitsArr.indexOf('allocatedSet:add') > -1 ||
      this.$store.state.buttonLimitsArr.indexOf('allocatedSet:update') > -1
  },
  methods: {
    ...mapActions(['getAreas', 'getIndustry']),
    handleScroll(e) {
      this.$nextTick(function () {
        if (
          this.$refs.tableBox &&
          this.$refs.tableBox.getBoundingClientRect().top < 128
        ) {
          // this.tableHeight = this.$refs.mainCon.getBoundingClientRect().height - 84
          this.tableHeight = window.innerHeight - 218

          if (document.getElementsByClassName('tableBoxCur').length) {
            document.getElementsByClassName('tableBoxCur')[0].style.height =
              null
          }
          this.hiddleToolBar = true
        } else {
          this.hiddleToolBar = false
        }
      })
    },
    getTableList(data) {
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isEmpty = true
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    searchTable() {
      this.loading = true
      this.$refs.pagination.getTableListData()
    },
    onAdd() {
      this.dialogTitle = '设置专户拨付计划条件'
      this.formData.id = ''
      this.formData.areaId = ''
      this.formData.industryArray = []
      this.formData.scale = ''
      this.formData.type = ''
      this.formArea = []
      this.dialogVisible = true
    },
    onUpdate(index, item) {
      this.dialogTitle = '修改专户拨付计划条件'
      this.getAllocatedById(item.id)
    },
    getAllocatedById(id) {
      this.axios({
        method: 'post',
        url: 'api-acc/cs/accassconfig/expand/findbyid',
        data: {
          id: id,
        },
      })
        .then((res) => {
          // formData.industryId
          let industrys = new Array(res.data.result.industryId)
          this.formData.id = res.data.result.id
          this.formData.areaId = res.data.result.areaId
          this.formData.industryArray = industrys
          this.formData.scale = res.data.result.scale
          this.formData.type = res.data.result.type
          this.formArea = res.data.result.areaId
          this.dialogVisible = true
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取专户拨付计划数据失败',
            type: 'error',
          })
        })
    },
    onDel(id) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.delAllocatedSet(id)
        })
        .catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        })
    },
    delAllocatedSet(id) {
      this.axios({
        method: 'post',
        url: 'api-acc/cs/accassconfig/expand/remove',
        data: {
          id: id,
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '删除成功',
                type: 'success',
              })
              this.$refs.pagination.getTableListData()
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    onSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 保存更新
          this.isSaveLoading = true
          this.submitForm()
        } else {
          return false
        }
      })
    },
    submitForm() {
      var data = {
        id: this.formData.id,
        areaId: this.formData.areaId,
        // industryArray: JSON.stringify(this.formData.industryArray),
        industryArray: this.formData.industryArray.toString(),
        scale: this.formData.scale,
        type: this.formData.type,
      }
      this.axios({
        method: 'post',
        url: 'api-acc/cs/accassconfig/expand/addoredit',
        data: data,
      })
        .then((response) => {
          this.isSaveLoading = false
          if (!response.data.hasError) {
            this.$refs.pagination.getTableListData()
            this.$message({
              message: '设置专户拨付计划条件成功',
              type: 'success',
            })
            this.handleClose()
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
            this.isSaveLoading = false
          }
        })
        .catch((error) => {
          this.$message.error('设置专户拨付计划条件失败')
          this.isSaveLoading = false
        })
    },
    //获取选中的区域最后一级id
    getAreaIdSearch() {
      this.filterField.areaId =
        this.filterFieldArea[this.filterFieldArea.length - 1]
    },
    getAreaId() {
      this.formData.areaId = this.formArea[this.formArea.length - 1]
    },

    getBursetype() {
      this.axios({
        method: 'post',
        url: 'api-acc/cs/accassconfig/expand/finddisbursetype',
      })
        .then((res) => {
          this.bursetype = res.data.result
        })
        .catch((error) => {
          this.$message({
            showClose: true,
            duration: 3000,
            message: '获取拨付方式数据失败',
            type: 'error',
          })
        })
    },
    closeDialog(ele) {
      this.$refs[ele].resetFields()
      this.handleClose()
    },
  },
}
</script>

<style lang="less" scoped>
.container {
  .el-form1 {
    margin-top: 20px; //修改搜索栏上下间距为24px
  }
}
@media screen and (min-width: 1280px) and (max-width: 1366px) {
  .searchInputWidth /deep/.el-form-item__label {
    width: 82px;
  }
}
.form-item {
  width: 300px;
}
@import '../../../static/css/filterArea.less';
.agreementBox {
  /deep/label {
    line-height: 20px;
  }
}
</style>
